package controllers.admin

import controllers.checkAdmin
import models.wifi.{WiFiInfo, WifiInfoRepository}

import javax.inject._
import play.api.Logging
import play.api.libs.json._
import play.api.mvc._

import scala.concurrent.{ExecutionContext, Future}

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class WiFiController @Inject()(cc: ControllerComponents,
                               wifiInfoRepository: WifiInfoRepository)(implicit exec: ExecutionContext, parser: BodyParsers.Default)
  extends AbstractController(cc) with play.api.i18n.I18nSupport with Logging {
  //implicit val myCustomCharset = Codec.javaSupported("gb18030")

  /**
   * Create an Action to render an HTML page with a welcome message.
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index() = Action.async { implicit request =>
    wifiInfoRepository.online.map { w =>
      Ok(views.html.users.wifi("tab", w))
    }
  }

  def manage() = checkAdmin(parser, exec).async { implicit request =>
    wifiInfoRepository.list.map { w =>
      Ok(views.html.admin.wifi("tab", w))
    }
  }

  def save() = checkAdmin(parser, exec).async { implicit request =>
    val req = request.body.asJson.getOrElse(Json.obj("op" -> "", "name" -> ""))
    logger.debug(request.body.toString())
    //Thread.sleep(5000)
    try {
      req("op").as[String] match {
        case "create" | "update" => {
          val name = req("name").as[String]
          val password = req("password").as[String]
          val note = (req \ "note").asOpt[String]
          val online = (req \ "online").asOpt[String]
          if (name.length > 20 || password.length > 32 || note.getOrElse("").length > 255) Future(Ok("name(20)/password(32)/note(255) is too long."))
          else wifiInfoRepository
            .insertOrUpdate(WiFiInfo(name = name, password = password, note,online.nonEmpty))
            .map { res =>
              Ok(s"create/update $res")
            }
        }
        case "delete" => {
          val name = req("name").as[String]
          if (name.length > 20) Future(Ok("name is too long."))
          wifiInfoRepository.delete(name).map {
            res => Ok(s"$name deleted $res")
          }
        }
        case "list" => wifiInfoRepository.list.map {
          res => {
            val count = res.length
            val data = res.map(
              r =>
                Json.obj(
                  "name" -> r.name,
                  "password" -> r.password,
                  "note" -> r.note,
                  "date" -> r.date.toLocalDateTime.toLocalDate.toString,
                  "online" -> (if (r.online) "是" else "否")
                )
            )
            Ok(Json.obj("code" -> 0, "message" -> "", "count" -> count, "data" -> Json.toJson(data)))
          }
        }
        case _ => Future(Ok("op error").flashing("success" -> "error"))
      }

    } catch {
      case exception: Exception => {
        logger.error(s"WiFiController.save request.body:${request.body.toString}", exception);
        Future(Ok("json error"))
      }
    }

  }

}
